<template>
	<view class="content">
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		<!--展开导航-->
		<view class="content-body">
			<view style="position: fixed;top: 0;z-index: 99;background: #fff;padding-bottom: 15rpx;box-sizing: border-box;width: 100%;padding-top: constant(safe-area-inset-top);padding-top: env(safe-area-inset-top);">
				<view class="body-nav">
					<view class="body-nav-list">
						<view class="body-nav-item" :class="{'avtive':type==1}" @click="changeType(1)">
							<view>{{$t('colony.navTitle1')}}</view>
							<view v-if="type==1" style="margin-left: 16rpx;">
								<u-image
									src="/static/images/icon/bottom-line.png"
									mode="scaleToFill"
									width="122rpx"
									height="12rpx"
								></u-image>
							</view>
							<view v-else style="height: 12rpx;"></view>
						</view>
						<view style="" class="body-nav-item" :class="{'avtive':type==0}" @click="changeType(0)">
							<view style="text-align: left;padding-left: 8rpx;">{{$t('colony.navTitle2')}}</view>
							<view v-if="type==0">
								<u-image
									src="/static/images/icon/bottom-line.png"
									width="122rpx"
									height="12rpx"
								></u-image>
							</view>
							<view v-else style="height: 12rpx;"></view>
						</view>
					</view>
					<view class="nav-tools">
						<view class="nav-item" @click="goSearch">
							<u-image
								src="/static/images/icon/search-2x.png"
								width="44rpx"
								height="44rpx"
							></u-image>
							<view class="nav-item-badge" v-if="msgNum>0">{{msgNum}}</view>
						</view>
						<view class="nav-item" @click="goChat">
							<u-image
								src="/static/images/icon/message.png"
								width="44rpx"
								height="44rpx"
							></u-image>
							<view class="nav-item-badge" v-if="msgNum>0">{{msgNum}}</view>
						</view>
						<view class="nav-item" @click="goNotice">
							<u-image
								src="/static/images/icon/clock.png"
								width="44rpx"
								height="44rpx"
							></u-image>
							<view class="nav-item-badge" v-if="noticeNum>0">{{noticeNum}}</view>
						</view>
						<view class="nav-item" @click="openLeftMenu">
							<u-image
								src="/static/images/icon/menu.png"
								width="44rpx"
								height="44rpx"
							></u-image>
						</view>
					</view>
				</view>
				<view v-if="showNav" style="width: 100%;display: flex;justify-content: space-between;box-sizing: border-box;align-items: center;padding:0 24rpx;">
					<view class="body-menu-list">
						<view :class="{'body-menu-item-active':tags_index==0,'body-menu-item':tags_index!=0}"
							@click="changeTab(0)"
						>{{$t('colony.navTitle3')}}</view>
						<view v-for="(item,index) in tags_list" :key="index" :class="{'body-menu-item-active':tags_index==item.id,'body-menu-item':tags_index!=item.id}"
							@click="changeTab(item.id)"
						>{{item.title}}</view>
					</view>
					<view style="margin-left: 20rpx;" @click="goFilter">
						<u-image
							src="/static/images/icon/right-icon.png"
							width="40rpx"
							height="40rpx"
						></u-image>
					</view>
				</view>
			</view>
		</view>
		<!--展开导航结束-->
		
		<!--内容-->
		<view class="content-body">
			<view v-if="type==1" style="width: 100%;display: flex;justify-content: space-between;box-sizing: border-box;align-items: center;padding:0 24rpx;">
				<view class="body-menu-list">
					<view :class="{'body-menu-item-active':tags_index==0,'body-menu-item':tags_index!=0}"
						@click="changeTab(0)"
					>全部</view>
					<view v-for="(item,index) in tags_list" :key="index" :class="{'body-menu-item-active':tags_index==item.id,'body-menu-item':tags_index!=item.id}"
						@click="changeTab(item.id)"
					>{{item.title}}</view>
				</view>
				<view style="margin-left: 20rpx;">
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			
			<view class="body-content">
				<card-list :listData="data_list" type="colony"></card-list>
				<view class="body-bottom" v-if="showBottom">
					<view class="text">已经到底了~</view>
				</view>
			</view>
		</view>
		<!--内容结束-->
		
		<!--排序-->
		<!-- <u-picker :show="sort_show" :columns="sort_list" @confirm="checkSort" @cancel="cancelSort" @close="cancelSort" :closeOnClickOverlay="true"></u-picker> -->
		<view v-show="sort_show">
			<view class="language" >
				<view class="language-card">
					<view class="language-list">
						<view v-for="(item, index) in sort_list" :key="index" class="language-item language-item-select">
							<view class="language-title" @click="changeSort(index)">{{item}}</view>
						</view>
					</view>
					<view class="language-footer">
						<view class="language-item language-item-btn" @click="sort_show=false">Cancel</view>
					</view>
				</view>
			</view>
		</view>
		<!--排序結束-->
		<!--发布选择弹窗-->
		<pushlish-popup ref="pushlishPopup" ></pushlish-popup>
		<!--发布选择弹窗结束-->
		<!--右側彈窗-->
		<left-menu-popup ref="leftMenuPopup" />
		<!--右側彈窗結束-->
	</view>
</template>

<script>
	import pushlishPopup from '@/components/publish-popup.vue';
	import leftMenuPopup from '@/components/left-menu-popup.vue';
	import cardList from '@/components/card-list.vue'
	import { indexList, getBanner, getTag, getMsg } from '@/config/api.js';
	
	export default {
		data() {
			return {
				userId: 0, // 添加userId
				order_by: 0, // 添加排序字段
				sort_name:'綜合',
				sort_show:false,
				sort_list:['綜合', '最新', '最熱門'],
				type:1,
				msgNum:0,
				noticeNum:0,
				banner_list:[],
				tags:'',
				tags_index:0,
				tags_list:[],
				data_list:[],
				page:1,
				max_page:0,
				city_name:'',
				current:0,
				scrollTop: 0,// 当前滚动位置
				hideThreshold: 174, // 隐藏轮播图的阈值（例如200px）
				showNav:true
			}
		},
		components: {
			pushlishPopup,leftMenuPopup,cardList
		},
		mounted(){
			uni.$on('showMidButtonPopup', () => {
				this.$refs.pushlishPopup.show();
			})
		},
		onReachBottom(){
			if( this.page <= this.max_page ){
				uni.showLoading({
					icon:'none',
					title:'請求中'
				})
				this.getData();
			}
		},
		onPullDownRefresh() {
			console.log('refresh');
			this.page = 1;
			this.data_list = [];
			this.getData();
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onLoad() {
			let uid = uni.getStorageSync('userId');
			this.city_id = uni.getStorageSync('cityId');
			this.city_name = uni.getStorageSync('cityName');
			if (uid > 0) {
				this.userId = uid;
			}
			this.initTags(); // 改为初始化标签方法
			this.page = 1;
			this.data_list = [];

			if (this.city_id == '') {
				// 默认查询台北
				this.city_id = 44;
				uni.setStorageSync('cityId', 44);
				uni.setStorageSync('cityName', '臺北');
			}
			this.getData();
		},
		onShow(){
			this.city_name = uni.getStorageSync('cityName');
			this.getNotice();
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			console.log(this.scrollTop)
			if(this.scrollTop > this.hideThreshold){
				this.showNav = false;
			} else {
				this.showNav = true;
			}
		},
		methods: {
			// 初始化标签数据
			initTags() {
				// 先尝试从本地缓存获取用户选择的标签
				const userSelectedTags = uni.getStorageSync('userSelectedTags');
			  
				if (userSelectedTags && userSelectedTags.length > 0) {
					// 使用用户选择的标签
					this.tags_list = userSelectedTags;
				} else {
					// 如果没有用户选择的标签，则获取全部标签
					this.getTagFn();
				}
			},
			//切換(熱門/追蹤)
			changeTab(tag_id){
				this.tags_index = tag_id;
				this.tags = tag_id;
				this.page = 1;
				this.data_list = [];
				
				this.getData();
			},
			//切換type
			changeType(type_id){
				this.type = type_id;
				this.page = 1;
				this.data_list = [];
				
				this.getData();
			},
			checkSort(res){
				console.log(res.value)
				this.sort_name = res.value[0]
				this.sort_show = false;
			},
			cancelSort(){
				this.sort_show = false;
			},
			//切換城市
			changeCity(){
				uni.navigateTo({
					url: '/pages/home/city',
					success: res => {},
					fail: () => {},
					complete: (res) => {
						console.log(res)
					}
				});
			},
			//獲取輪播圖
			getBannerFn(){
				let data = {}
				getBanner(data).then((res) => {
					//success
					for( let obj in res.data ){
						this.banner_list.push(res.data[obj].image);
					}
				}).catch(() =>{
					
				})
			},
			//獲取Tag
			getTagFn(){
				let data = {
					type:2
				}
				let that = this
				getTag(data).then((res) => {
					//success
					that.tags_list = res
				}).catch(() =>{
					
				})
			},
			getNotice(){
				let that = this;
				let userId = uni.getStorageSync('userId');
				if( userId > 0 ){
					let data = {
						data:{
							userid:userId
						}
					}
					
					getMsg(data).then((res) => {
						//success
						console.log(res)
						that.msgNum = res.chat_num;
						that.noticeNum = res.num;
					}).catch(() =>{
						
					})
				}
			},
			//加載數據
			getData(){
				let that = this;
				uni.showLoading({
					title: '加载中...'
				})
				let data = {
				    page: this.page,
				    type: 3, // 1达人,2任务,3社区
				    track: this.type, // 1推荐,0追踪
				    category: this.tags, // 标签(宠物,形象)
				    orderby: this.order_by, // 添加排序参数
				    city: this.city_id // 使用id,避免多语言城市无法查询
				}
				indexList({data: data}).then((res) => {
				    // success
				    console.log('getData', res.data)
				    if (that.page == 1) {
				      that.data_list = [];
				    }
				    that.data_list = that.data_list.concat(res.data);
				    that.max_page = res.total_pages; // 改为total_pages
				    that.page++;
				    uni.hideLoading();
				}).catch(() => {
				    
				})
			},
			openLeftMenu() {
			  if (this.userId > 0) {
			    this.$refs.leftMenuPopup.show();
			  } else {
			    this.goLogin()
			  }
			},
			
			goNotice() {
			  if (this.userId > 0) {
			    uni.navigateTo({
			      url: '/pages/my/notice'
			    })
			  } else {
			    this.goLogin()
			  }
			},
			
			goChat() {
			  if (this.userId > 0) {
			    uni.navigateTo({
			      url: '/pages/my/chat'
			    })
			  } else {
			    this.goLogin()
			  }
			},
			
			goLogin() {
			  uni.navigateTo({
			    url: '/pages/index/login'
			  })
			},
			goSearch(){
				uni.navigateTo({
					url:'/pages/home/search'
				})
			},
			goFilter() {
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/filter',
					events: {
						// 监听filter页面返回的数据
						acceptDataFromFilter: (data) => {
							console.log('接收filter页面数据:', data);
							if (data && data.selectedTags) {
								// 更新标签列表为用户选择的标签
								that.tags_list = data.selectedTags;
								// 保存到本地缓存
								uni.setStorageSync('userSelectedTags', data.selectedTags);
								// 重置为第一个标签
								that.tags_index = 0;
								that.tags = '';
								// 重新加载数据
								that.page = 1;
								that.data_list = [];
								that.getData();
							}
						}
					},
					success: (res) => {
						// 传递当前标签列表到filter页面
						res.eventChannel.emit('sendCurrentTags', {
							currentTags: that.tags_list
						});
					}
				})
			},
			changeSort(e){
				console.log(e)
				//0:綜合,1最新,2最熱門
				//更新數據
				this.page = 1;
				this.order_by = e;
				this.data_list = [];
				this.getData();
				//更新排序名稱
				this.sort_name = this.sort_list[e];
				this.sort_show = false;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		background: linear-gradient( 180deg, #C9F2FF 0%, #F6F8FA 6%);
		font-family: PingFang TC, PingFang TC;
	}
	.nav{
		width: 100%;
		margin-top: 12rpx;
		
		.nav-header{
			display: flex;
			justify-content: space-between;
			padding: 0 32rpx;
			
			.nav-left{
				display: flex;
				justify-content: flex-start;
				box-sizing: border-box;
				align-items: center;
				
				.nav-map{
					// width: 80rpx;
					// height: 80rpx;
					// padding: 16rpx 0;
				}
				.nav-search{
					margin-left: 16rpx;
					width: 380rpx;
				}
			}
			
			.nav-tools{
				display: flex;
				justify-content: space-between;
				margin-left: 16rpx;
				.nav-item{
					position: relative;
					display: inline-block;
					margin: 0 10rpx;
					padding: 15rpx 0;
					.nav-item-badge{
						position: absolute;
						top: 0px; /* 根据需要调整 */
						right: -10rpx; /* 根据需要调整 */
						background-color: #FF3D43;
						color: white;
						border-radius: 50%; /* 圆形 */
						width: 40rpx; /* 根据需要调整 */
						height: 40rpx; /* 根据需要调整 */
						display: flex;
						justify-content: center;
						align-items: center;
						font-size: 22rpx; /* 根据需要调整 */
					}
				}
			}
		}
		.nav-banner{
			margin: 40rpx auto 0;
			width: 682rpx;
		}
	}
	.content-body{
		width: 100%;
		margin-top: 40rpx;
		background: linear-gradient(to bottom, #FFF 2%, #eceeef);
		border-top-left-radius: 50rpx;
		border-top-right-radius: 50rpx;
		.body-nav{
			width: 100%;
			display: flex;
			justify-content: space-between;
			font-size: 32rpx;
			color: #808690;
			font-weight: 500;
			padding: 32rpx 26rpx 20rpx 0;
			box-sizing: border-box;
			
			.body-nav-list{
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
				
				.body-nav-item{
					// margin: 0 64rpx 0 0;
					text-align: center;
					font-family: -apple-system, PingFang TC, sans-serif;
					font-weight: 500;  /* Medium字重对应500 */
					width:170rpx
				}
				.avtive{
					font-weight: 500;
					color: #232426;
				}
			}
			.nav-tools{
				display: flex;
				justify-content: space-between;
				margin-left: 16rpx;
				.nav-item{
					position: relative;
					display: inline-block;
					margin: 0 10rpx;
					padding: 15rpx 0;
					.nav-item-badge{
						position: absolute;
						top: 0px; /* 根据需要调整 */
						right: -10rpx; /* 根据需要调整 */
						background-color: #FF3D43;
						color: white;
						border-radius: 50%; /* 圆形 */
						width: 40rpx; /* 根据需要调整 */
						height: 40rpx; /* 根据需要调整 */
						display: flex;
						justify-content: center;
						align-items: center;
						font-size: 22rpx; /* 根据需要调整 */
					}
				}
			}
		}
		.body-menu-list{
			display: flex;
			justify-content: flex-start;
			// padding: 0 16rpx;
			box-sizing: border-box;
			overflow-x: auto;
			font-size: 28rpx;
			
			.body-menu-item{
				color: #808690;
				padding: 8rpx 20rpx;
				flex-shrink: 0;
				margin-right:16rpx;
			}
			.body-menu-item-active{
				color: #188CA2;
				background-color: #EEF7FD;
				border-radius: 40rpx;
				padding: 8rpx 20rpx;
				flex-shrink: 0;
				margin-right:16rpx;
			}
		}
		.body-content{
			margin-top: 90rpx;
			padding:0 23rpx;
			background-color: #FFF;
			min-height: 980rpx;
			
			.body-bottom{
				text-align: center;
				padding: 56rpx 0;
				width: 100%;
				
				.text{
					color: #BEC0C5;
					font-size: 28rpx;
				}
			}
		}
	}
	
	.indicator{
		justify-content: center;
		@include flex(row);
		
		&__dot {
			height: 8rpx;
			width: 32rpx;
			border-radius: 4rpx;
			background-color: rgba(255, 255, 255, 0.35);
			margin: 0 6px;
			transition: background-color 0.3s;

			&--active {
				background-color: #ffffff;
			}
		}
	}
	
	.language{
		position: fixed; /* 固定定位 */
		top: 0;
		left: 0;
		width: 100%; /* 宽度100% */
		height: 100%; /* 高度100% */
		background-color: rgba(0, 0, 0, 0.3);
		z-index: 999;
	}
	.language-card{
		position: fixed;
		bottom: 68rpx;
		left: 50%;
		transform: translateX(-50%);
		z-index: 9999;
		width: 718rpx;
	}
	.language-list{
		
	}
	.language-list .language-item-select:first-of-type{
		border-radius: 24rpx 24rpx 0 0;
		border-bottom: 1rpx solid #ADADAD;
	}
	.language-list .language-item-select:last-of-type{
		border-radius: 0 0 24rpx 24rpx;
		border-top: 1rpx solid #ADADAD;
	}
	.language-item{
		padding: 34rpx 0;
		background: rgb(255, 255, 255);
		text-align: center;
		margin: 0 auto;
	}
	.language-title{
		color: #007AFF;
		font-size: 34rpx;
	}
	.language-footer{
		margin-top: 16rpx;
	}
	.language-item-btn{
		font-weight: 600;
		color: #007AFF;
		border-radius: 24rpx;
	}
</style>
